<template>
    <div style="min-width: 829px">
        <div v-if="$route.path == '/orderAccom'">
            <div class="vs-search-box">
                <el-form
                    ref="form"
                    :inline="true"
                    :model="paging"
                    label-width="110px"
                >
                    <el-form-item label="门店：">
                        <el-select
                            v-model="paging.store_id"
                            style="width: 250px"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in shopList"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="顾客姓名：">
                        <el-input
                            style="width: 250px"
                            placeholder="支持任意关键字搜索"
                            v-model="paging.username"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="" class="vs-right-btns">
                        <el-button @click="reset">重置</el-button>
                        <el-button
                            @click="handleCurrentChange(1)"
                            type="primary"
                            >查询</el-button
                        >
                    </el-form-item>
                    <el-form-item label="手机号码：">
                        <el-input
                            style="width: 250px"
                            placeholder="支持手机尾号4位搜索"
                            v-model="paging.phone"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="订单编号：">
                        <el-input
                            style="width: 250px"
                            placeholder="支持订单后4位搜索"
                            v-model="paging.out_trade_no"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="房间号：">
                        <el-input
                            style="width: 250px"
                            placeholder=""
                            v-model="paging.room"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="床位号：">
                        <el-input
                            style="width: 250px"
                            placeholder=""
                            v-model="paging.bed"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="服务技师：">
                        <el-input
                            style="width: 250px"
                            placeholder=""
                            v-model="paging.staff_id"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="开单日期：">
                        <el-date-picker
                            style="width: 250px"
                            range-separator="至"
                            v-model="paging.bill_date_start"
                            value-format="yyyy-MM-dd"
                            type="daterange"
                            placeholder=""
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="开单时间：">
                        <el-time-picker
                            is-range
                            style="width: 250px"
                            v-model="paging.bill_time_start"
                            range-separator="至"
                            value-format="HH:mm:ss"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder=""
                        >
                        </el-time-picker>
                    </el-form-item>
                    <el-form-item label="预约方式：">
                        <el-select
                            style="width: 250px"
                            clearable
                            v-model="paging.mode"
                            placeholder="请选择"
                        >
                            <el-option label="大众点评" value="0"> </el-option>
                            <el-option label="小程序" value="1"> </el-option>
                            <el-option label="电话" value="2"> </el-option>
                            <el-option label="我的管家" value="3"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="项目名称：">
                        <el-input
                            style="width: 250px"
                            v-model="paging.project_name"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="vs-table-box">
                <div class="operation-box clear-float">
                    <el-button
                        style="margin-left: auto"
                        icon="el-icon-download"
                        :loading="isDerive"
                        @click="derive"
                        >导出</el-button
                    >
                </div>
                <el-table
                    v-loading="loading"
                    :data="tableData"
                    header-row-class-name="has-gutter-table"
                    style="width: 100%"
                >
                    <el-table-column
                        prop="out_trade_no"
                        label="订单编号"
                        min-width="120"
                    ></el-table-column>
                    <el-table-column
                        prop="bill_date"
                        label="开单日期"
                        width="100"
                    ></el-table-column>
                    <el-table-column
                        prop="bill_time"
                        label="开单时间"
                        width="80"
                    ></el-table-column>
                    <el-table-column label="项目名称" min-width="130">
                        <template slot-scope="scope">
                            <span>{{ scope.row.projectOne.project_name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="服务技师" min-width="120">
                        <template
                            slot-scope="scope"
                            v-if="scope.row.projectOne.staff"
                        >
                            {{ scope.row.projectOne.staff.name }}（{{
                                scope.row.projectOne.staff.number
                            }}）
                        </template>
                    </el-table-column>
                    <el-table-column label="排钟类型">
                        <template slot-scope="scope">
                            {{ scope.row.projectOne.staff_type | staffType }}
                        </template>
                    </el-table-column>
                    <el-table-column label="房间号">
                        <template
                            slot-scope="scope"
                            v-if="scope.row.projectOne.room"
                        >
                            {{ scope.row.projectOne.room.room_number }}
                        </template>
                    </el-table-column>
                    <el-table-column label="床位号">
                        <template
                            slot-scope="scope"
                            v-if="scope.row.projectOne.bed"
                        >
                            {{ scope.row.projectOne.bed.number }}
                        </template>
                    </el-table-column>
                    <el-table-column label="顾客姓名" min-width="120">
                        <template slot-scope="scope" v-if="scope.row.user">
                            {{ scope.row.user.username }}
                        </template>
                    </el-table-column>
                    <el-table-column label="手机号" min-width="130">
                        <template slot-scope="scope" v-if="scope.row.user">
                            {{ scope.row.user.phone }}
                        </template>
                    </el-table-column>
                    <el-table-column label="预约方式">
                        <template slot-scope="scope">
                            <span v-if="scope.row.reserve">
                                {{ scope.row.reserve.mode | typeMode }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="预付金额">
                        <template slot-scope="scope">
                            {{ scope.row.advance_amount }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单总额（元）">
                        <template slot-scope="scope">
                            {{ scope.row.orders_payable }}
                        </template>
                    </el-table-column>
                    <el-table-column label="支付方式" min-width="140">
                        <template slot-scope="scope">
                            <!-- {{ payType(scope.row.pay_type) }} -->
                             <!-- 1余额 2微信 3支付宝 -->
                            <span v-if="scope.row.pay_type == 1">余额</span>
                            <span v-if="scope.row.pay_type == 2">微信</span>
                            <span v-if="scope.row.pay_type == 3">支付宝</span>
                            <!-- <span
                                @click="setPayType(scope.row)"
                                class="tab-table-text"
                                >修改</span
                            > -->
                        </template>
                    </el-table-column>
                    <el-table-column label="实体卡券/备注" min-width="120" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <el-image
                                v-if="scope.row.entity_image"
                                class="image-thumbnail"
                                :src="scope.row.entity_image"
                                fit="cover"
                                :preview-src-list="[scope.row.entity_image]"
                            >
                            </el-image>
                            <span v-else-if="scope.row.entity_code">{{ scope.row.entity_code }}</span>
                            <span v-else>{{ scope.row.pay_remarks }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单状态">
                        <template slot-scope="scope">
                            {{ scope.row.status | orderStatus }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="备注">
                    <template slot-scope="scope">
                    <span v-if="scope.row.reserve">
                        {{scope.row.reserve.remark}}
                    </span>
                     </template>
                </el-table-column> -->
                    <el-table-column prop="return_money" label="退款金额">
                    </el-table-column>
                    <el-table-column fixed="right" width="110" label="操作">
                        <template slot-scope="scope">
                            <span @click="setRow(1,scope.row)" class="tab-table-text">详情</span>
                            <span
                                v-if="
                                    scope.row.is_invoice == 0 &&
                                    (scope.row.pay_type == 2 ||
                                        scope.row.pay_type == 3 ||
                                        scope.row.pay_type == 4 ||
                                        scope.row.pay_type == 5)
                                "
                                @click="setRow(3, scope.row)"
                                class="tab-table-text"
                                >开票</span
                            >
                            <span class="tab-red-text"  v-if="scope.row.status != 11"  @click="cancelOrder(scope.row)">作废</span>
                             <!-- <span class="tab-huang-text">修改</span> -->
                            <!-- <span v-if="scope.row.status != 7&&scope.row.status != 9" @click="setRow(2,scope.row)" class="tab-red-text">退款</span> -->
                        </template>
                    </el-table-column>
                </el-table>
                <div class="vs-paging-box">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page.sync="paging.page"
                        :page-size="paging.limit"
                        layout="sizes,prev, pager, next, jumper"
                        :total="paging.total"
                    >
                    </el-pagination>
                </div>
            </div>
        </div>
        <router-view></router-view>
        <el-dialog
            title="修改支付方式"
            :visible.sync="dialogVisible2"
            width="450px"
            :close-on-click-modal="false"
            :before-close="handleClose2"
        >
            <el-form
                :model="pay"
                :rules="rules"
                ref="payform"
                label-width="100px"
                class="code-form"
            >
                <el-form-item label="负责人姓名" prop="phone">
                    <el-select
                        style="width: 210px"
                        v-model="pay.phone"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in shopList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.phone"
                        >
                        </el-option>
                    </el-select>
                    <div @click="getCode" class="code-box">
                        <span v-if="isCode">获取验证码</span>
                        <span v-else>{{ codesSec }}秒</span>
                    </div>
                </el-form-item>
                <el-form-item prop="pay_code" label="验证码">
                    <el-input
                        type="age"
                        v-model.number="pay.pay_code"
                        style="width: 100%"
                        maxlength="6"
                        placeholder="请输入6位验证码"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="支付方式" prop="pay_type">
                    <el-select
                        style=""
                        v-model="pay.pay_type"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in payWay"
                            :key="item.type"
                            :label="item.title"
                            :value="item.type"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose2()">取 消</el-button>
                <el-button type="primary" @click="setOrderPayType(1)"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
        <el-dialog
            title="申请退款"
            :visible.sync="dialogVisible"
            :before-close="handleClose"
        >
            <el-form
                ref="form"
                v-if="order.user"
                :model="form"
                :rules="rules"
                label-width="120px"
            >
                <el-form-item label="订单编号：" prop="use_status">
                    {{ order.out_trade_no }}
                </el-form-item>
                <el-form-item label="顾客项目：" prop="use_status">
                    {{ order.user.username }}
                </el-form-item>
                <el-form-item label="手机号码：" prop="use_status">
                    {{ order.user.phone }}
                </el-form-item>
                <el-form-item label="可退款金额：" prop="use_status">
                    {{ order.orders_payable - order.return_money }}
                </el-form-item>
                <el-form-item label="退款金额：" prop="return_money">
                    <el-input
                        v-model.number="form.return_money"
                        @input="priceInput"
                        placeholder="请输入退款金额"
                    ></el-input>
                </el-form-item>
                <el-form-item label="退款原因：" prop="return_remark">
                    <el-input
                        type="textarea"
                        :rows="5"
                        v-model="form.return_remark"
                        placeholder="请输入退款金额"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose()">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            recordList: [],
            loading: false,
            loading2: false,
            shopList: [],
            isBtn: false,
            isInfo: false,
            dialogVisible: false,
            isDerive: false,
            dialogVisible2: false,
            payWay: [
                {
                    type: 1,
                    title: "免单支付",
                    icon: "icon-free",
                },
                {
                    type: 2,
                    title: "现金结账",
                    icon: "icon-xianjinzichan",
                },
                {
                    type: 3,
                    title: "银行卡",
                    icon: "icon-yinhangqia-xianxing",
                },
                {
                    type: 4,
                    title: "微信",
                    icon: "icon-yinhangqia-xianxing",
                },
                {
                    type: 5,
                    title: "支付宝",
                    icon: "icon-yinhangqia-xianxing",
                },
                {
                    type: 6,
                    title: "会员卡余额",
                    icon: "icon-yue1",
                },
                {
                    type: 7,
                    title: "大众点评（团购）",
                    icon: "icon-tuangou",
                },
                {
                    type: 8,
                    title: "大众点评（预定）",
                    icon: "icon-yuyue",
                },
                {
                    type: 16,
                    title: "大众点评",
                    icon: "icon-yue1",
                },
                {
                    type: 9,
                    title: "口碑",
                    icon: "icon-koubei",
                },
                {
                    type: 10,
                    title: "WOW",
                    icon: "icon-wow",
                },
                {
                    type: 11,
                    title: "小程序",
                    icon: "icon-xiaochengxu",
                },
                {
                    type: 12,
                    title: "实体卡券",
                    icon: "icon-qiaquan",
                },
                {
                    type: 15,
                    title: "次卡",
                    icon: "icon-yingchengka",
                },
                {
                    type: 13,
                    title: "正大无限卡",
                    icon: "icon-yingchengka",
                },
                {
                    type: 14,
                    title: "其他",
                    icon: "icon-yingchengka",
                },
            ],
            paging: {
                store_id: "",
                is_market: 0, //1商场订单 0项目订单
                status: "", //是否是已完成订单 传参：4
                is_complete: 1,
                username: "", //顾客姓名
                phone: "", //手机号
                out_trade_no: "", //订单编号
                room: "", //房间id
                bed: "", //床位id
                staff_id: "", //技师id
                mode: "", //预约方式 0大众点评 1小程序 2电话 3我的管家
                project_name: "", //项目名称
                bill_date_start: "", //开单日期 开始
                bill_date_end: "", //开单日期 结束
                bill_time_start: "", //开单时间 开始
                bill_time_end: "", //开单时间 结束
                page: 1,
                total: 0,
                limit: 10,
            },
            order: {},
            pay:{
                id:'',
                phone:'',//手机号
                pay_type:'',//支付方式
                pay_code:'',//验证码
            },
            isCode:true,
            codesSec:60,
            intCode:-1,
            form: {
                id: "", //订单id
                return_money: "", //退款金额
                return_remark: "", //退款备注
            },
            rules: {
                phone: { required: true, message: '请选择负责人', trigger: 'change' },
                pay_type: { required: true, message: '请选择支付方式', trigger: 'change' },
                pay_code: { required: true, message: '请输入验证码', trigger: 'blur' },

                return_money: { required: true, message: "请输入退款金额", trigger: "blur", },
                return_remark: { required: true, message: "请输入退款备注", trigger: "blur", },
            },
            isDerive: false,
            tableData: [],
        };
    },
    created() {
        if (this.$route.path == "/orderAccom") {
            this.homegetStore();
        }
    },
    methods: {
        setPayType(row) {
            this.pay.id = row.id;
            this.pay.pay_type = Number(row.pay_type);
            this.dialogVisible2 = true;
        },
        setOrderPayType(){
            this.$refs['payform'].validate(async (valid) => {
                if (!valid) return;
                let { code, data } = await this.$Http.setOrderPayType(this.pay);
                if (code) {
                    this.$message.success("修改订单支付方式成功!");
                    this.handleClose2();
                    this.repairGetList();
                }
            })
        },
        // 订单作废
        async cancelOrder(row){
            this.$msgbox({
                    title: '提示',
                    message: '确定要作废该订单吗?',
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose:async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            let { code, data } = await this.$Http.updateWaste({id:row.id})
                            if(code){
                                this.$message.success("订单已作废")
                                this.homegetStore();
                            }
                            done();
                            instance.confirmButtonLoading = false;
                        } else {
                            done();
                        }
                    }
                }).then(action => {

                }).catch(()=>{});
        },
        handleClose2(dom) {
        //   this.form = this.$options.data().form;
        this.$refs["payform"].resetFields();
        this.dialogVisible2 = false;
        dom && dom();
        },
        async getCode() {
            if (!this.isCode) return;
            if (!this.pay.phone) return this.$message.error('请选择负责人')
            this.isCode = false;
            let { code, data } = await this.$Http.ordersPaySms(this.pay)
            if (code) {
                this.$message.success('验证码已发送,注意查收')
            } else return this.isCode = true;
            this.codesSec = 60;
            this.intCode = setInterval(() => {
                this.codesSec--;
                if (this.codesSec <= 0) {
                    clearInterval(this.intCode);
                    this.isCode = true;
                }
            }, 1000);
        },
        payType(types) {
            types = types.split(",");
            let val = [];
            for (let i in types) {
                let v = this.payWay.find((v) => v.type == types[i]);
                if (v) {
                    val.push(v.title);
                }
            }
            return val.join(",");
        },
        async derive() {
            let obj = Object.assign({}, this.paging);
            // delete obj.limit;
            delete obj.page;
            delete obj.total;
            obj.is_all = 1;
            if( obj.bill_date_start){
                obj.bill_date_end = obj.bill_date_start[1];
                obj.bill_date_start = obj.bill_date_start[0];
            }else{
                obj.bill_date_end = "";
                obj.bill_date_start = "";
            }

            if(obj.bill_time_start){
                obj.bill_time_end = obj.bill_time_start[1];
                obj.bill_time_start = obj.bill_time_start[0];
            }else{
                obj.bill_time_end = "";
                obj.bill_time_start = "";
            }
            this.isDerive = true;
            let res = await this.$Http.exportOrders(obj);
            this.utils.downloadXlsx(res, "订单");
            this.isDerive = false;
        },
        async homegetStore() {
            let { code, data } = await this.$Http.homegetStore();
            if (code) {
                // this.paging.store_id = data[0].id;
                this.shopList = data;
                this.handleCurrentChange(1);
            }
        },
        priceInput() {
            if (
                this.form.return_money >
                this.order.orders_payable - this.order.return_money
            ) {
                this.form.return_money =
                    this.order.orders_payable - this.order.return_money;
            }
        },
        submit() {
            this.$refs["form"].validate(async (valid) => {
                if (!valid) return;
                let obj = Object.assign({}, this.form);
                let { code, data } = await this.$Http.ordersReturn(obj);
                if (code) {
                    this.$message.success("提交成功!");
                    this.handleCurrentChange(1);
                    this.handleClose();
                }
            });
        },
        handleClose(dom) {
            this.form = this.$options.data().form;
            this.$refs["form"].resetFields();
            this.dialogVisible = false;
            dom && dom();
        },
        openInfo() {
            this.$prompt("请输入核验码", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                inputPattern: /^[0-9]\d{5}$/,
                inputErrorMessage: "核验码格式不正确",
                beforeClose: async (action, instance, done) => {
                    console.log(instance, "actionactionaction");
                    if (action === "confirm") {
                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = "执行中...";
                        let { code, data } = await this.$Http.checkOrder({
                            check_code: instance.inputValue,
                        });
                        if (code) {
                            this.$message.success("提交成功!");
                            this.handleCurrentChange(1);
                        }
                        done();
                        instance.confirmButtonLoading = false;
                    } else {
                        done();
                    }
                },
            })
                .then(({ value }) => {})
                .catch(() => {});
        },
        async setRow(type, row) {
            if (type == 1) {
                this.utils.goUrl(
                    "/finishOrderInfo?title=订单详情&type=2&id=" + row.id
                );
            } else if (type == 3) {
                // 开票
                if (row.isEnd) {
                    this.$message.warning("此次消费开票有效期为30天");
                    return;
                }
                this.utils.goUrl(
                    `/makeInvoice?company_id=${row.store.company_id}&orders_id=${row.id}&price=${row.orders_payable}`
                );
            } else {
                this.dialogVisible = true;
                this.order = row;
                this.form.id = row.id;
                this.form.return_money = row.return_money;
            }
        },
        async repairGetList() {
            let obj = Object.assign({}, this.paging);
            if( obj.bill_date_start){
                obj.bill_date_end = obj.bill_date_start[1];
                obj.bill_date_start = obj.bill_date_start[0];
            }else{
                obj.bill_date_end = "";
                obj.bill_date_start = "";
            }

            if(obj.bill_time_start){
                obj.bill_time_end = obj.bill_time_start[1];
                obj.bill_time_start = obj.bill_time_start[0];
            }else{
                obj.bill_time_end = "";
                obj.bill_time_start = "";
            }

            this.loading = true;
            let { code, data } = await this.$Http.ordersgetOrders(obj);
            this.loading = false;
            if (code) {
                data.data.forEach((v) => {
                    if (v.entity_image == "0") v.entity_image = "";
                    v.isEnd = false;
                    if (v.pay_time) {
                        // 起止时间
                        let presentTime = Date.parse(new Date()) / 1000;
                        // 截止时间
                        var date = new Date(v.pay_time);
                        var time = new Date(
                            date.setDate(date.getDate() + 30)
                        ).toLocaleDateString(); //获取当前日期后加30天
                        let getEndTime = new Date(time);
                        let endTime = Date.parse(getEndTime) / 1000;
                        if (presentTime > endTime) {
                            v.isEnd = true;
                        }
                        console.log(presentTime, endTime, v.isEnd);
                    }
                    v.projectOne = v.project.length ? v.project[0] : {};
                });
                this.tableData = data.data;
                this.paging.total = data.total;
            }
        },
        reset() {
            //重置
            this.paging = this.$options.data().paging;
            // this.paging.store_id = this.shopList[0].id;
            this.handleCurrentChange(1);
        },
        handleSizeChange(val) {
            this.paging.limit = val;
            this.repairGetList();
        },
        handleCurrentChange(val) {
            this.paging.page = val;
            this.repairGetList();
        },
    },
};
</script>

<style lang="scss" scoped>
.image-thumbnail {
    width: 60px;
    height: 60px;
}
</style>